<template>
  <div class="app-container">
    <div class="page-header">
      <h2>企业微信二维码管理</h2>
      <p>维护企微客服二维码信息</p>
    </div>

    <div class="content-area">
      <el-card>
        <div slot="header" class="card-header">
          <span>二维码列表</span>
          <el-button type="primary" size="small" @click="handleAdd">
            <i class="el-icon-plus" /> 新建
          </el-button>
        </div>

        <el-table
          v-loading="loading"
          :data="list"
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="#" width="60" align="center" />
          <el-table-column label="应用" min-width="160">
            <template slot-scope="scope">
              <span>{{ appnameMap[scope.row.appname] || scope.row.appname }}</span>
            </template>
          </el-table-column>

          <el-table-column label="二维码" min-width="160">
            <template slot-scope="scope">
              <el-image
                v-if="scope.row.image"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                style="width: 60px; height: 60px; object-fit: contain; border: 1px solid #eee"
              />
              <span v-else>—</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="560px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="应用" prop="appname">
          <el-input :value="appnameMap[form.appname] || form.appname" disabled />
        </el-form-item>

        <el-form-item label="二维码" prop="image">
          <div style="display:flex; align-items:center; gap:12px;">
            <el-image
              v-if="form.image"
              :src="form.image"
              style="width: 100px; height: 100px; object-fit: contain; border: 1px solid #eee"
            />
            <ImgCutter :box-height="700" :cut-width="700" :cut-height="700" @cutDown="onCutDown">
              <template #open>
                <el-button type="primary">裁切上传 (700x700)</el-button>
              </template>
            </ImgCutter>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCustomerList, saveCustomer } from '@/api/yunyin'
import ImgCutter from 'vue-img-cutter'
import axios from 'axios'

export default {
  name: 'QrcodeManage',
  components: { ImgCutter },
  data() {
    return {
      loading: false,
      submitting: false,
      list: [],
      page: 1,
      appnameMap: {
        '310Android': '310大师',
        'yqty': '有球体育',
        'xqk': '星球客'
      },
      appnameOptions: [
        { value: '310Android', label: '310大师' },
        { value: 'yqty', label: '有球体育' },
        { value: 'xqk', label: '星球客' }
      ],
      dialogVisible: false,
      dialogTitle: '新建',
      form: {
        id: null,
        appname: '',
        name: '',
        image: '',
        status: '1'
      },
      rules: {
        image: [{ required: true, message: '请上传二维码图片', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    async fetchList() {
      this.loading = true
      try {
        const res = await getCustomerList({ page: this.page })
        this.list = (res && res.data) || []
      } catch (e) {
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    handleAdd() {
      this.dialogTitle = '新建'
      this.form = { id: null, appname: '', name: '', image: '', status: '1' }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑'
      this.form = { id: row.id, appname: row.appname, name: row.name, image: row.image, status: row.status }
      this.dialogVisible = true
    },
    async onCutDown(v) {
      try {
        const formData = new FormData()
        formData.append('image', v.file)
        const response = await axios.post('https://api.zctj16888.com/admin/v1/image/ossUpload', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        const url = response && response.data && response.data.data && response.data.data.url
        if (!url) throw new Error('upload failed')
        this.form.image = url
        this.$message.success('上传成功')
      } catch (err) {
        this.$message.error('上传失败')
      }
    },
    async handleStatusChange(row, value) {
      try {
        await saveCustomer({ id: row.id, appname: row.appname, name: row.name, image: row.image, status: value })
        this.$message.success('状态已更新')
      } catch (e) {
        this.$message.error('更新状态失败')
        const revertValue = value === '1' ? '0' : '1'
        this.$set(row, 'status', revertValue)
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate(async(valid) => {
        if (!valid) return
        this.submitting = true
        try {
          await saveCustomer({ ...this.form })
          this.$message.success('保存成功')
          this.dialogVisible = false
          this.fetchList()
        } catch (e) {
          this.$message.error('保存失败')
        } finally {
          this.submitting = false
        }
      })
    }
  }
}
</script>

<style scoped>
.page-header {
  margin-bottom: 16px;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>

